package com.tenement.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.tenement.base.constants.SysmConstants.existed;
import com.tenement.base.exception.ParameterException;
import com.tenement.mybatis.dao.HouseMapper;
import com.tenement.mybatis.dao.ReserveMapper;
import com.tenement.mybatis.entity.House;
import com.tenement.mybatis.entity.Reserve;
import com.tenement.service.interfaces.IReserveService;
import com.tenement.utils.base.ProduceUtil;
import com.tenement.utils.phonemsg.SendPhoneVerifyCodeUtil;

@Service("IReserveService")
public class ReserveServiceImpl implements IReserveService {

	@Autowired
	private ReserveMapper reserveMapper;
	
	@Autowired
	private HouseMapper houseMapper;

	/**
	 * 用户预约看房操作
	 */
	@Override
	public boolean userReserveHouses(Reserve reserve,String userName,String userPhoneNumber) {
		Reserve r = new Reserve();
		try {
			if (reserve == null) {
				throw new ParameterException("【房源详情-预约看房功能-传参为空reserve】");
			}
			if (userName == null||"".equals(userName)) {
				throw new ParameterException("【房源详情-预约看房功能-传参为空userName】");
			}
			if (userPhoneNumber == null||"".equals(userPhoneNumber)) {
				throw new ParameterException("【房源详情-预约看房功能-传参为空userPhoneNumber】");
			}
			
			House house = houseMapper.selectByPrimaryKey(reserve.gethId());
			String phoneNumberTo = house.gethTelephone();//获取该房源信息房主留下的联系方式
			//发送手机预约看房通知,预约人联系方式,接收方,联系人姓名
			SendSmsResponse sendSmsResponse = SendPhoneVerifyCodeUtil.sendSms(userPhoneNumber,phoneNumberTo,userName); 
			if(sendSmsResponse.getCode() != null && sendSmsResponse.getCode().equals("OK")){
				r.sethId(house.gethId());
				r.setuLandlord(house.getuId());
				r.setuId(reserve.getuId());			
				r.setrReservedate(ProduceUtil.productNowDate());
				int i = reserveMapper.userReserveHouses(r);
				if(i>0){
					return true;
				}else{
					return false;
				}
			}
		} catch (ParameterException | ClientException p) {
			p.printStackTrace();
		}
		return false;
	}

	/**
	 * 判断用户是否已经预约该房源
	 */
	@Override
	public String judgeIsReserved(Reserve reserve) {
		try {
			if (reserve == null) {
				throw new ParameterException("【房源详情-判断用户是否预约房源-传参为空】");
			}
			Reserve r = reserveMapper.judgeIsReserved(reserve);
			if (r == null) {
				return existed.No;
			} else {
				return existed.Yes;
			}
		} catch (ParameterException p) {
			p.printStackTrace();
		}
		return existed.No;
	}

}
